using System;
using System.Windows.Forms;
using IronPython.Hosting;
using MEA.AE_Data.Config;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;

namespace MEA.AE_BusinessLogic
{
	public class ScriptingLayer
	{
		private ScriptingInterface scriptIF;

		private ScriptEngine _engine;

		private ScriptRuntime _runtime;

		private ScriptScope _scope;

		private ScriptSource _source;

		private MyErrorListener _errorLis = new MyErrorListener();

		public ScriptingLayer(ServiceLayer servicelayer)
		{
			scriptIF = new ScriptingInterface(servicelayer);
			_engine = Python.CreateEngine();
			_runtime = _engine.Runtime;
			_scope = _engine.CreateScope();
			_scope.SetVariable("E4W_Script", scriptIF);
		}

		public void ScriptRun(object sender, ServiceLayerStringEventArg e)
		{
			try
			{
				string[] array = new string[0];
				array = (e.Message.Contains("\r\n") ? e.Message.Split('\r', '\n') : ((!e.Message.Contains("\n")) ? new string[1] { e.Message } : e.Message.Split('\n')));
				string text = string.Empty;
				string[] array2 = array;
				foreach (string text2 in array2)
				{
					string text3 = text2.Replace("\n", "");
					text3 = text3.Replace("\r", "");
					text3 = text3.Replace("\t", "  ");
					text = ((text.Length != 0) ? (text + "\r\n" + text3) : (text + text3));
				}
				if (!string.IsNullOrEmpty(text))
				{
					_source = _engine.CreateScriptSourceFromString(text, SourceCodeKind.Statements);
					_source.Compile(_errorLis);
					if (_errorLis.ErrorCode != 0)
					{
						MessageBox.Show(string.Format("Discription {0} \r\nError at Line No.{1} and Column No{2}", _errorLis.Message, _errorLis.Span.Start.Line, _errorLis.Span.Start.Column));
					}
					else
					{
						_source.Execute(_scope);
					}
				}
			}
			catch (Exception exception)
			{
				ExceptionOperations service = _engine.GetService<ExceptionOperations>(new object[0]);
				MessageBox.Show("Error when parsing script:\r\n" + service.FormatException(exception), ConfigData.WizardSwName);
			}
		}
	}
}
